# 少量噪声定位图片
import cv2
import numpy as np

print('loading  ...')
unit = 3


def showpiclocation(img, findimg):
    # 定位图片
    w = img.shape[1]
    h = img.shape[0]
    fw = findimg.shape[1]
    fh = findimg.shape[0]
    findpt = None
    for now_h in range(0, int((h / unit) - fh)):
        for now_w in range(0, int((w / unit) - fw)):
            comp_tz = img[now_h * unit:now_h * unit + fh, now_w * unit:now_w * unit + fw, :] - findimg
            if abs(np.mean(comp_tz)) < 100:
                # 0 = {int} 303 120
                findpt = now_w * unit, now_h * unit
                print("ok")
        print('.')
    if findpt != None:
        cv2.rectangle(img, findpt, (findpt[0] + fw, findpt[1] + fh), (0, 0, 255))
    return img


def fastFind(img, findimg, precision = 0.0000000005):


    # opencv模板匹配----单目标匹配
    # 获得模板图片的高宽尺寸
    theight, twidth = findimg.shape[:2]
    # 执行模板匹配，采用的匹配方式cv2.TM_SQDIFF_NORMED
    result = cv2.matchTemplate(img, findimg, cv2.TM_SQDIFF_NORMED)
    # 归一化处理
    cv2.normalize(result, result, 0, 1, cv2.NORM_MINMAX, -1)
    # 寻找矩阵（一维数组当做向量，用Mat定义）中的最大值和最小值的匹配结果及其位置
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    if (min_val > precision or min_val < -precision):
        return -1
    # 匹配值转换为字符串
    # 对于cv2.TM_SQDIFF及cv2.TM_SQDIFF_NORMED方法min_val越趋近与0匹配度越好，匹配位置取min_loc
    # 对于其他方法max_val越趋近于1匹配度越好，匹配位置取max_loc
    return min_loc


def addnoise(img):  # 为图像添加噪声
    coutn = 50000
    for k in range(0, coutn):
        xi = int(np.random.uniform(0, img.shape[1]))
        xj = int(np.random.uniform(0, img.shape[0]))
        img[xj, xi, 0] = 255 * np.random.rand()
        img[xj, xi, 1] = 255 * np.random.rand()
        img[xj, xi, 2] = 255 * np.random.rand()

# fn='pictest.png'
# fn1='pictestt1.png'
#
# myimg=cv2.imread(fn)
# myimg1=cv2.imread(fn1)
#
# addnoise(myimg)         		  #添加噪声
# myimg=showpiclocation(myimg,myimg1)     #图像定位
#
# cv2.namedWindow('img')
# cv2.imshow('img', myimg)
# cv2.waitKey()
# cv2.destroyAllWindows()
